﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Composite.Events;
using Microsoft.Practices.Composite.Wpf.Commands;
using RAD.Modules.Scripts.PresentationModels;
using Users.Interfaces;
using RAD.Modules.Scripts.Interfaces;
using RAD.Infrastructure;

namespace Users.Views
{
    public class UsersPresenter : IScriptsPresenter
    {
        private readonly RADRICommandProxy _commandProxy;
        private readonly IScriptService _scriptService;
        private IEventAggregator _eventAggregator { get; set; }
        protected DelegateCommand<string> _scriptRun;

        public IScriptsView View { get; set; }

        public UsersPresenter(IScriptsView view, 
                                IScriptService scriptService, 
                                RADRICommandProxy commandProxy,
                                IEventAggregator eventAggregator)
        {
            View = view;
            _commandProxy = commandProxy;
            _scriptService = scriptService;
            _eventAggregator = eventAggregator;

            _scriptRun = new DelegateCommand<string>(ScriptRun);
            
            _commandProxy.ScriptRunCommand.RegisterCommand(_scriptRun);
            InitializeEvents();
        }

        private void InitializeEvents()
        {
            
        }

        private void ScriptRun(object parameter)
        {
            if (View.ScriptListBox.SelectedItem != null)
            {
                ScriptItem script = (ScriptItem)View.ScriptListBox.SelectedItem;
                _scriptService.ScriptRun(script);
                if (_scriptService.ScriptProcess != null)
                    _scriptService.ScriptProcess.WaitForExit();

                _eventAggregator.GetEvent<UpdateConsoleEvent>().Publish("123"); 
            }
        }
    }
}
